package cn._2dland.sakushi;

import java.util.Collection;
import java.util.HashSet;

/**
 * 请求信息类
 * @author deadblue
 */
public class Request {
	/** 问题 */
	private String problem = null;
	/** 选项 */
	private Collection<String> choices = new HashSet<String>();
	/** 是否需要图表 */
	private boolean chart = false;

	public Request() {}

	/**
	 * 判断请求是否为空
	 * @return
	 */
	public boolean isEmpty() {
		return (problem==null || "".equals(problem) || choices.isEmpty());
	}

	public void setProblem(String problem) {
		this.problem = problem;
	}
	public String getProblem() {
		return problem;
	}

	public void setNeedChart(boolean needChart) {
		this.chart = needChart;
	}
	public boolean isNeedChart() {
		return chart;
	}

	public void addChoice(String choice) {
		choices.add(choice);
	}
	public Collection<String> getChoices() {
		return choices;
	}

	/**
	 * 解析文本，并返回请求对象
	 * @param text 文本
	 * @return
	 * @throws Exception
	 */
	public static Request parse(String text) {
		// 判断是否需要图表
		boolean chart = text.endsWith(" /c");
		if(chart)
			text = text.substring(0, text.length() - 3);

		Request req = new Request();
		//req.setNeedChart(chart);
		req.setNeedChart(false);
		// 解析文本
		StringBuffer buf = new StringBuffer();
		boolean getQuestion = false;
		for(int i=0; i<text.length(); i++) {
			char c = text.charAt(i);
			if(!getQuestion && (c == '？' || c == '?')) {
				// 设置问题，并重置缓冲区
				req.setProblem(buf.toString());
				getQuestion = true;
				buf = new StringBuffer();
			} else if(getQuestion && (c =='；' || c == ';')) {
				req.addChoice(buf.toString());
				buf = new StringBuffer();
			} else {
				buf.append(c);
			}
		}
		// 循环结束时，若缓冲区不为空，将其作为一个选项
		if(buf.length() > 0) req.addChoice(buf.toString());

		return req;
	}
}